package com.jackaltsc.mydemodatastorage.internalstorage;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.jackaltsc.mydemodatastorage.R;

public class InternalActivity extends Activity implements OnClickListener {

    private static final String FILENAME = "FileTestInternal";
    private Button btnWrite, btnRead;
    private EditText etDataWrite;
    private TextView tvDataRead;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_internal);

        initView();

    }

    private void initView() {

        btnWrite = (Button) findViewById(R.id.btn_internal_write);
        btnRead = (Button) findViewById(R.id.btn_internal_read);

        etDataWrite = (EditText) findViewById(R.id.et_inter_datawrite);
        tvDataRead = (TextView) findViewById(R.id.tv_inter_dataread);

        initEvent();

    }

    private void initEvent() {

        btnWrite.setOnClickListener(this);
        btnRead.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {

            case R.id.btn_internal_write:
                String dataw = etDataWrite.getText().toString();
                funInternalWrite(dataw, FILENAME);
                break;

            case R.id.btn_internal_read:
                String datar = funInternalRead(FILENAME);
                tvDataRead.setText(datar);
                break;

        }

    }

    /**
     * 写入数据到内部存储
     *
     * @param wData    数据
     * @param filename 写入到的文件
     */
    private void funInternalWrite(String wData, String filename) {

        FileOutputStream fos;

        try {

            fos = openFileOutput(filename, Context.MODE_PRIVATE);
            fos.write(wData.getBytes());
            fos.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private String funInternalRead(String filename) {

        String rData = "";

        try {

            FileInputStream fis = openFileInput(filename);
            byte[] bytes = new byte[fis.available()];
            fis.read(bytes);
            fis.close();

            rData = new String(bytes);

        } catch (IOException e) {
            e.printStackTrace();
        }
        return rData;
    }
}
